/*
 * Copyright 2010 Interactive Media Management
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.i2m.converge.core.newswire;

import dk.i2m.converge.core.security.UserAccount;
import dk.i2m.converge.core.plugin.NewswireDecoder;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.Transient;
import org.eclipse.persistence.annotations.PrivateOwned;

/**
 * {@link Entity} representing a news feed to include in the newswire service.
 *
 * @author Allan Lykke Christensen
 */
@Entity
@Table(name = "newswire_service")
@NamedQueries({
    @NamedQuery(name = NewswireService.COUNT_SUBSCRIBERS, query = "select count(ns.subscribers) from NewswireService ns where ns.id=:id"),
    @NamedQuery(name = NewswireService.COUNT_ITEMS, query = "select count(ns.items) from NewswireService ns where ns.id=:id")})
public class NewswireService implements Serializable {

    public static final String COUNT_SUBSCRIBERS = "NewswireService.countSubscribers";

    public static final String COUNT_ITEMS = "NewswireService.countItems";

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "source")
    private String source = "";

    @Column(name = "url") @Lob
    private String url = "";

    @Column(name = "decoder_class") @Lob
    private String decoderClass = "";

    @Temporal(javax.persistence.TemporalType.TIMESTAMP)
    @Column(name = "last_fetch")
    private Calendar lastFetch;

    @OneToMany(mappedBy = "newswireService", fetch = FetchType.LAZY)
    @PrivateOwned
    private List<NewswireItem> items = new ArrayList<NewswireItem>();

    @ManyToMany(mappedBy = "newswireServices", fetch = FetchType.LAZY)
    private List<UserAccount> subscribers = new ArrayList<UserAccount>();

    @javax.persistence.Version
    @Column(name = "opt_lock")
    private int versionIdentifier;

    @OneToMany(mappedBy = "newswireService", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @PrivateOwned
    private List<NewswireServiceProperty> properties = new ArrayList<NewswireServiceProperty>();

    @Transient
    private Long numberOfSubscribers = 0L;

    @Transient
    private Long numberOfItems = 0L;

    /**
     * Creates a new instance of {@link NewswireService}.
     */
    public NewswireService() {
    }

    /**
     * Creates a new instance of {@link NewswireService}.
     *
     * @param source
     *          Source of the {@link NewswireService}
     * @param url
     *          URL of the {@link NewswireService}
     */
    public NewswireService(String source, String url) {
        this.source = source;
        this.url = url;
    }

    /**
     * Gets the unique ID of the {@link NewswireService}.
     * 
     * @return Unique ID of the {@link NewswireService}
     */
    public Long getId() {
        return id;
    }

    /**
     * Sets the unique ID of the {@link NewswireService}. This method should not be invoked manually as {@link NewFeed}s are
     * automatically assigned identifiers by the database.
     * 
     * @param id
     *          Unique ID of the {@link NewswireService}
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * Gets the source of the {@link NewswireService}.
     *
     * @return Source of the {@link NewswireService}
     */
    public String getSource() {
        return source;
    }

    /**
     * Sets the source of the {@link NewswireService}. The source appears next to each of the items in the feed. It would
     * typically be a read-friendly name.
     * 
     * @param source
     *          Source of the {@link NewswireService}
     */
    public void setSource(String source) {
        this.source = source;
    }

    /**
     * Gets the classname of the decoder used for the service.
     *
     * @return Classname of the decoder used for the service
     */
    public String getDecoderClass() {
        return decoderClass;
    }

    /**
     * Sets the classname of the decoder used for the service.
     *
     * @param decoderClass
     *          Classname of the decoder
     */
    public void setDecoderClass(String decoderClass) {
        this.decoderClass = decoderClass;
    }

    /**
     * Creates an instance of the decoder specified in {@link NewswireService#getDecoderClass()}.
     *
     * @return Instance of the decoder
     * @throws NewswireDecoderException
     *          If the decoder could not be instantiated
     */
    public NewswireDecoder getDecoder() throws NewswireDecoderException {
        try {
            Class c = Class.forName(getDecoderClass());
            NewswireDecoder decoder = (NewswireDecoder) c.newInstance();
            return decoder;
        } catch (ClassNotFoundException ex) {
            throw new NewswireDecoderException("Could not find connector: " + getDecoderClass(), ex);
        } catch (InstantiationException ex) {
            throw new NewswireDecoderException("Could not instantiate connector [" + getDecoderClass() + "]. Check to ensure that the decoder has a public contructor with no arguments", ex);
        } catch (IllegalAccessException ex) {
            throw new NewswireDecoderException("Could not access connector: " + getDecoderClass(), ex);
        }
    }

    /**
     * Gets the URL of the {@link NewswireService}.
     *
     * @return URL of the {@link NewswireService}
     */
    public String getUrl() {
        return url;
    }

    /**
     * Sets the URL of the {@link NewswireService}.
     *
     * @param url
     *          URL of the {@link NewswireService}
     */
    public void setUrl(String url) {
        this.url = url;
    }

    public List<NewswireItem> getItems() {
        return items;
    }

    public void setItems(List<NewswireItem> newswireItems) {
        this.items = newswireItems;
    }

    public List<UserAccount> getSubscribers() {
        return subscribers;
    }

    public void setSubscribers(List<UserAccount> subscribers) {
        this.subscribers = subscribers;
    }

    public Calendar getLastFetch() {
        return lastFetch;
    }

    public void setLastFetch(Calendar lastFetch) {
        this.lastFetch = lastFetch;
    }

    public int getVersionIdentifier() {
        return versionIdentifier;
    }

    public void setVersionIdentifier(int versionIdentifier) {
        this.versionIdentifier = versionIdentifier;
    }

    public List<NewswireServiceProperty> getProperties() {
        return properties;
    }

    public void setProperties(List<NewswireServiceProperty> properties) {
        this.properties = properties;
    }

    public Long getNumberOfSubscribers() {
        return this.numberOfSubscribers;
    }

    public Long getNumberOfItems() {
        return this.numberOfItems;
    }

    public void setNumberOfItems(Long numberOfItems) {
        this.numberOfItems = numberOfItems;
    }

    public void setNumberOfSubscribers(Long numberOfSubscribers) {
        this.numberOfSubscribers = numberOfSubscribers;
    }

    /**
     * Gets a {@link Map} containing the properties of the service.
     *
     * @return {@link Map} containing the properties of the service
     */
    public Map<String, String> getPropertiesMap() {
        Map<String, String> map = new HashMap<String, String>();
        for (NewswireServiceProperty property : this.properties) {
            map.put(property.getKey(), property.getValue());
        }

        return map;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final NewswireService other = (NewswireService) obj;
        if (this.id != other.id
                && (this.id == null || !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 31 * hash + (this.id != null ? this.id.hashCode() : 0);
        return hash;
    }

    @Override
    public String toString() {
        return getClass().getName() + "[id=" + id + "]";
    }
}
